#!/usr/bin/ruby -d

require 'gserver'
require 'tempfile'
require 'taskmgr'

class SMTPServer < GServer
  TEMPDIR = "/tmp"

  def serve(io)
    @data_mode = false
    io.print "220 hello\r\n"
    tmpfile = Tempfile.new('smtpd', TEMPDIR)
    loop do
      if IO.select([io], nil, nil, 0.1)
        data = io.readpartial(4096)
        ok, op = process_line(data, tmpfile)
        break unless ok
        io.print op
      end
      break if io.closed?
    end
    io.print "221 bye\r\n"
    tmpfile.rewind
    m = TMail.new(tmpfile)
    processmail = Thread.new do
      m.process
    end
    tmpfile.close
    tmpfile.delete
    io.close
    processmail.join
  end

  def process_line(line, file)
    if (line =~ /^(HELO|EHLO)/i)
      return true, "220 and..?\r\n"
    end
    if (line =~ /^QUIT/)
      return false, "bye\r\n"
    end
    if (line =~ /^MAIL FROM\:/)
      return true, "220 OK\r\n"
    end
    if (line =~ /^RCPT TO\:/)
      return true, "220 OK\r\n"
    end
    if (line =~ /^DATA/)
      @data_mode = true
      return true, "354 Enter message, ending with \".\" on a line by itself\r\n"
    end
    if (@data_mode)
      file.puts line
      if (line.chomp =~ /^.$/)
        @data_mode = false
        return true, "220 OK\r\n"
      else
        return true, ""
      end
    else
      return true, "500 ERROR\r\n"
    end
  end
end

